import os
import threading
from tkinter import Button

import json

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except, wrapCmd
from util.env.java.jar_util import delayed_open_url
from util.window.config_window.config_button import create_config_button
from util.comm.path import getConfigPath
from util.comm.msg_util import msg
import tkinter as tk


class WinExecTool():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getConfigPath()
        self.button = create_config_button(self, True)

        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        if isinstance(data, list):
            for index, c in enumerate(data):
                if 'is_active' in c:
                    if c['is_active'] == 0:
                        continue
                # 增加二级目录
                self.menu = self.create_tab(self.tab, c['menu'])
                self.elements.append(self.menu)
                content = c['content']
                if isinstance(content, list):
                    row = 1
                    column = 0
                    for index, conf in enumerate(content):
                        if 'is_active' in conf:
                            if conf['is_active'] == 0:
                                continue
                        # 增加三级内容
                        name = conf['name']
                        self.button = Button(self.menu, text=name, command=lambda n=name,c=conf: self.print_entry_sync(n,c), width=12)
                        self.button.grid(row=row, column=column, padx=5, pady=5)
                        column += 1
                        if column % 4 == 0:  # 每四个按钮换行
                            column = 0
                            row += 1
                            new_row = tk.Frame(self.menu)
                            new_row.grid(row=row, column=column, sticky='news')
                        # self.button.pack(side='left', fill=None, expand=False, anchor='ne', padx=20, pady=30)

        else:
            print(data)

    def print_entry_sync(self, n, config):
        flag = "sync_flag_%s" % n
        if hasattr(self, flag) and getattr(self, flag) == '1':
            msg('正在处理,请勿重复操作')
            return
        setattr(self, flag, '1')
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(config,)), lambda n=n: self.reset_sync(n)).execute_async()

    def reset_sync(self, n):
        flag = "sync_flag_%s" % n
        setattr(self, flag, '0')

    def print_entry(self, config):
        cmd = config['path']
        s = config['shell']
        if 'url' in config and config['url'] is not None and config['url'] != "":
            # 判断文件是否存在
            if not os.path.exists(cmd):
                url = config['url']
                msg("执行文件【%s】不存在，请去【%s】下载" % (cmd, url))
                threading.Thread(target=delayed_open_url, args=(url, 2,)).start()
                return
        is_shell = True
        # cmd = handleCmdExe(cmd)
        cmd = '"%s"' % cmd
        print(cmd)
        if s == '0':
            is_shell = False
        wrapCmd(f"{cmd}", is_shell)

    def create_tab(self, master_tabs, title):
        # 创建第一级tab t1
        tree_tab = tk.Frame(master_tabs)
        tree_tab.pack()

        master_tabs.add(tree_tab, text=title)
        return tree_tab

def handleCmdExe(cmd):
    index = cmd.rfind('\\')
    if index != -1:
        path = cmd[0:index]
        # path = path.replace("\\", "\\\\\\")
        exe = cmd[index+1:]
        # cmd = "cd \"%s\" && %s" % (path, exe)

        fd = cmd[0:1]
        cmd = "cd \"%s\" && %s: && .\\%s" % (path, fd, exe)
    return cmd

if __name__ == '__main__':
    cmd = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Notepad++.lnk"
    cmd = handleCmdExe(cmd)
    print(cmd)
    wrapCmd(f"{cmd}")
